package by.gusto.afisha.net;

import java.io.BufferedInputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class PageDownloader {

	private static final int BUFFER_SIZE = 4 * 1024;
	
	public static String getPage(final String url) {
		HttpClient client = new DefaultHttpClient();
		HttpResponse response = null;
		try {
			 response = client.execute(new HttpGet(url));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (response != null) {
			try {
				BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent());
				byte[] buffer = new byte[BUFFER_SIZE];
				int length = 0;
				StringBuffer sb = new StringBuffer();
				while ((length = bis.read(buffer)) != -1) {
					sb.append(new String(buffer, 0, length));
				}
				return sb.toString();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "";
	}
	
	public static void getPage(final String url, final IDownloadListener listener) {
		Thread t = new Thread(new Runnable() {
			
			@Override
			public void run() {
				String page = getPage(url);
				listener.onComplite(page);
			}
		});
		t.start();
	}
	
	interface IDownloadListener {
		void onComplite(String page);
	}
}
